//
//  SelectTemplateSubView.swift
//  CreateMyCode
//
//  Created by zhibao on 2024/2/20.
//

import UIKit
typealias SelectTemplateBlock = (_ dic:[String:Any])->()
class SelectTemplateSubView: LazyScrollSubView,UICollectionViewDelegate,UICollectionViewDataSource {
    var selectBlock:SelectTemplateBlock?
    var itemWH:CGFloat  = 0
    var margin:CGFloat = 0
    var dic = [AnyHashable:Any]()
    var flag = true
    let layout = UICollectionViewFlowLayout()
    var collectionView:MYCollectionView!
    var array = [[String:Any]]()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    override func reloadData(withDict dict: [AnyHashable : Any]!) {
        dic = dict
        if flag {
            flag = false
            self.initView()
            self.getData()
        }
    }
    
    fileprivate func getData(){
        let title = dic["title"] as! String
        if title == LocalizedString("点阵"){
            for i in 0 ..< 10 {
                let value = "pattern_\(i)"
                let dic = [
                    "img":value,
                    "value":value.replacingOccurrences(of: "_", with: "")
                ]
                array.append(dic)
            }
            collectionView.reloadData()
        }else if title == LocalizedString("图标") {
            
            HttpHelper.sharedInstance().sendGet("api/logo", parameters: [:]) { operation, responseObject in
                if responseObject.code != 1 {
                    return
                }
                let repData1 = responseObject.data as! [String:Any]
                let data =  repData1["data"] as? [String]
                for i in 0 ..< (data?.count ?? 0) {
                    let dic = [
                        "img":data?[i] ?? "",
                        "value":data?[i] ?? ""
                    ]
                    self.array.append(dic)
                }
                self.collectionView.reloadData()
            } failure: { operation, error in
                
            }
            let addDic = [
                "img":"plus.circle",
                "value":ADDFLAG
            ]
            array.append(addDic)
        }else if title == LocalizedString("模版") {
            HttpHelper.sharedInstance().sendGet("api/template", parameters: ["categoryId":dic["id"] ?? ""]) { operation, responseObject in
                if responseObject.code != 1 {
                    return
                }
                let repData1 = responseObject.data as! [String:Any]
                let data =  repData1["data"] as? [[String:Any]]
                self.array = data ?? [[String:Any]]()
                self.collectionView.reloadData()
            } failure: { operation, error in
                
            }
        }
        let firstDic = [
            "img":"trash",
            "value":CLEARFLAG
        ]
        array.append(firstDic)
        DLog(message: "array==\(array)")
    }
    
    fileprivate func initView(){
        layout.scrollDirection = .horizontal
        collectionView = MYCollectionView(frame: self.bounds, collectionViewLayout: layout)
        collectionView.alwaysBounceVertical = false
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.contentInset = UIEdgeInsets(top: 0, left: 10, bottom: 10, right: 0)
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.removeMJRefresh()
        collectionView.keyboardDismissMode = .onDrag
        self.addSubview(collectionView)
        collectionView.noDataType = .TableViewNoDataType_FILE
        collectionView.mj_footer?.endRefreshingWithNoMoreData()
        collectionView.register(TZTestCell.self, forCellWithReuseIdentifier: "TZTestCell1")
        collectionView.register(TZTestCell.self, forCellWithReuseIdentifier: "TZTestCell2")
        collectionView.register(TZTestCell.self, forCellWithReuseIdentifier: "TZTestCell3")
        collectionView.register(TZTestCell.self, forCellWithReuseIdentifier: "TZTestCell4")
        layout.itemSize = CGSizeMake(pixw(p: 60), pixw(p: 60))
        margin = pixw(p: 10)
        layout.minimumInteritemSpacing = margin
        layout.minimumLineSpacing = margin
        self.collectionView.collectionViewLayout = layout
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
extension SelectTemplateSubView{
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return array.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let tempDic = array[array.count - 1 -  indexPath.row]
        var cell:TZTestCell!
        if tempDic["demo_url"] != nil {
            cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TZTestCell1", for: indexPath) as? TZTestCell
            let imgUrl = tempDic["demo_url"] as! String
            cell.imageView.yy_setImage(with: URL(string: imgUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!), options: .showNetworkActivity)
            
        }else if tempDic["img"] != nil {
            let imgUrl = tempDic["img"] as! String
            if imgUrl.hasPrefix("http"){
                cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TZTestCell2", for: indexPath) as? TZTestCell
                cell.imageView.yy_setImage(with: URL(string: imgUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!), options: .showNetworkActivity)
            }else{
                cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TZTestCell3", for: indexPath) as? TZTestCell
//                let title = tempDic["title"] as! String
                if imgUrl.hasPrefix("pattern_"){
                    cell.imageView.image = UIImage(named: imgUrl)
                }else{
                    cell.imageView.image = nil
                    cell.deleteBtn.setImage(UIImage(systemName: imgUrl), for: .normal)
                    cell.deleteBtn.isUserInteractionEnabled = false
                }
            }
        }else{
            let imgUrl = tempDic["img"] as! String
            cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TZTestCell4", for: indexPath) as? TZTestCell
            cell.imageView.yy_setImage(with: URL(string: imgUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!), options: .showNetworkActivity)
        }
        cell.gifLable.isHidden = true
        cell.deleteBtn.tag = indexPath.item
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let tempDic = array[array.count - 1 -  indexPath.row]
        if selectBlock != nil {
            selectBlock!(tempDic)
        }
    }
}
